﻿using Mate.Caching;
using Mate.Db.Model.Info;
using Mate.Db.SqlSugar;
using Mate.Dto.Info;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mate.Merchant.Service
{
    public class DistrictService : DataService<mp_district>, IDistrictService
    {
        private readonly ICacheManager _cache;
        public DistrictService(DataClient dataClient, ICacheManager cache) : base(dataClient)
        {
            this._cache = cache;
        }

        #region 获取地区信息Tree列表
        /// <summary>
        /// 获取地区信息Tree列表
        /// </summary>
        /// <param name="is_open">1启用2禁用</param>
        /// <returns></returns>
        public IList<DistrictTreeModel> GetDistrictTree(int? is_open=null)
        {
            var list = Queryable.Where(x => x.is_delete == 1)
                .WhereIF(is_open!=null,x=>x.is_open==is_open.Value)
                .ToList();
            if (list == null || list.Count == 0)
            {
                return null;
            }
            return DistrictTreeItem(list, 0);
        }

        private List<DistrictTreeModel> DistrictTreeItem(IList<mp_district> list, int parentid)
        {
            return list.Where(x => x.parentid == parentid).Select((x, i) =>
            {
                return new DistrictTreeModel()
                {
                    id = x.id,
                    districtname = x.districtname,
                    parentid = x.parentid,
                    is_open=x.is_open,
                    children = list.Any(y => y.parentid == x.id) ? DistrictTreeItem(list, x.id).ToList() : null
                };
            }).ToList();
        }
        #endregion

    }
}
